<template>
  <view class="container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-input-box">
        <uni-icons type="search" size="18" color="#999"></uni-icons>
        <input 
          class="search-input" 
          type="text" 
          v-model="keyword" 
          placeholder="搜索商家、美食" 
          confirm-type="search"
          @confirm="handleSearch"
          focus
        />
        <uni-icons 
          v-if="keyword" 
          type="close" 
          size="18" 
          color="#999"
          @click="clearKeyword"
        ></uni-icons>
      </view>
      <text class="cancel-btn" @click="goBack">取消</text>
    </view>
    
    <!-- 搜索历史和热门搜索 -->
    <view v-if="!isSearched" class="search-guide">
      <!-- 搜索历史 -->
      <view v-if="searchHistory.length > 0" class="search-section">
        <view class="section-header">
          <text class="section-title">搜索历史</text>
          <uni-icons type="trash" size="20" color="#999" @click="clearHistory"></uni-icons>
        </view>
        <view class="tag-list">
          <view 
            class="tag-item" 
            v-for="(item, index) in searchHistory" 
            :key="index"
            @click="selectHistory(item)"
          >{{ item }}</view>
        </view>
      </view>
      
      <!-- 热门搜索 -->
      <view class="search-section">
        <view class="section-header">
          <text class="section-title">热门搜索</text>
        </view>
        <view class="tag-list">
          <view 
            class="tag-item" 
            v-for="(item, index) in hotKeywords" 
            :key="index"
            @click="selectHistory(item)"
          >{{ item }}</view>
        </view>
      </view>
    </view>
    
    <!-- 搜索结果 -->
    <view v-else class="search-result">
      <!-- 搜索条件筛选 -->
      <view class="filter-bar">
        <view 
          class="filter-item" 
          :class="{'active': sortType === 'default'}"
          @click="setSortType('default')"
        >综合排序</view>
        <view 
          class="filter-item" 
          :class="{'active': sortType === 'sales'}"
          @click="setSortType('sales')"
        >销量优先</view>
        <view 
          class="filter-item" 
          :class="{'active': sortType === 'distance'}"
          @click="setSortType('distance')"
        >距离优先</view>
      </view>
      
      <!-- 商户列表 -->
      <view class="merchant-list">
        <view 
          class="merchant-item" 
          v-for="(item, index) in searchResult" 
          :key="index"
          @click="goToMerchantDetail(item.id)"
        >
          <image class="merchant-logo" :src="item.logo" mode="aspectFill"></image>
          <view class="merchant-info">
            <view class="merchant-name">{{ item.name }}</view>
            <view class="merchant-rating">
              <!-- 评分暂时隐藏 -->
              <!-- <text class="rating-score">{{ item.rating }}</text>
              <text class="rating-text">分</text> -->
              <text class="sales-text">月售{{ item.sales }}+</text>
            </view>
            <view class="merchant-meta">
              <text class="distance">{{ item.distance }}km</text>
              <text class="delivery-time">{{ estimateTime(item.baseTime, item.distance) }}</text>
            </view>
          </view>
        </view>
        
        <!-- 空状态 -->
        <view v-if="searchResult.length === 0" class="empty-state">
          <image src="/static/icons/empty.png" mode="aspectFit" class="empty-icon"></image>
          <text class="empty-text">没有找到相关商家，换个关键词试试~</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import estimateTime from '@/utils/time.js';
import { getMerchantPage } from '@/api/merchant.js';
import uniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue';
import { getCurrentLocation, setCurrentLocation, fetchLocationList } from '@/utils/location.js';

// 搜索相关数据
const keyword = ref('');
const isSearched = ref(false);
const sortType = ref('default');
const searchHistory = ref([]);
const hotKeywords = ref(['奶茶', '水果', '快餐', '早餐', '甜点', '炒饭']);
const searchResult = ref([]);
let currentLocation = ref(null);

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 清空搜索关键词
const clearKeyword = () => {
  keyword.value = '';
  if (isSearched.value) {
    isSearched.value = false;
  }
};

// 选择历史搜索词或热门搜索词
const selectHistory = (item) => {
  keyword.value = item;
  handleSearch();
};

// 清空搜索历史
const clearHistory = () => {
  searchHistory.value = [];
  // 存储到本地
  uni.setStorageSync('searchHistory', JSON.stringify([]));
};

// 执行搜索
const handleSearch = async() => {
  if (!keyword.value.trim()) return;
  
  // 标记为已搜索状态
  isSearched.value = true;
  
  // 添加到搜索历史
  if (!searchHistory.value.includes(keyword.value)) {
    searchHistory.value.unshift(keyword.value);
    // 保留最近10条
    if (searchHistory.value.length > 10) {
      searchHistory.value = searchHistory.value.slice(0, 10);
    }
    // 存储到本地
    uni.setStorageSync('searchHistory', JSON.stringify(searchHistory.value));
  }
  // 从缓存获取位置
    currentLocation = await getCurrentLocation();
  // 调用接口获取商户数据
  getMerchantPage({
    keyword: keyword.value,
    sortType: sortType.value,
    latitude: currentLocation.latitude,
    longitude: currentLocation.longitude
  }).then(res => {
    searchResult.value = res.data.list;
  });
};

// 设置排序方式
const setSortType = (type) => {
  sortType.value = type;
  // 调用接口获取商户数据
  getMerchantPage({
    keyword: keyword.value,
    sortType: sortType.value,
    latitude: currentLocation.latitude,
    longitude: currentLocation.longitude
  }).then(res => {
    searchResult.value = res.data.list;
  });
};



// 跳转到商户详情
const goToMerchantDetail = (id) => {
  uni.navigateTo({
    url: `/pages/merchant/detail?id=${id}`
  });
};

// 页面加载时，获取本地存储的搜索历史
onMounted(() => {
  try {
    const history = uni.getStorageSync('searchHistory');
    if (history) {
      searchHistory.value = JSON.parse(history);
    }
  } catch (e) {
    console.error('获取搜索历史失败', e);
  }
});
</script>

<style lang="scss" scoped>
.container {
  background-color: #f0f2f5;
  min-height: 100vh;
}

/* 搜索头部 */
.search-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
}

.search-input-box {
  flex: 1;
  height: 72rpx;
  background-color: #f7f7f7;
  border-radius: 36rpx;
  display: flex;
  align-items: center;
  padding: 0 20rpx;
}

.search-input {
  flex: 1;
  height: 100%;
  font-size: 28rpx;
  margin: 0 20rpx;
  color: #333;
}

.cancel-btn {
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #666;
}

/* 搜索指引区域 */
.search-guide {
  padding: 20rpx 30rpx;
}

.search-section {
  margin-bottom: 40rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
}

.tag-item {
  padding: 10rpx 30rpx;
  background-color: #fff;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
  font-size: 26rpx;
  color: #666;
  border: 1rpx solid #eee;
}

/* 搜索结果区域 */
.filter-bar {
  display: flex;
  background-color: #fff;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
  position: sticky;
  top: 112rpx;
  z-index: 9;
}

.filter-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.filter-item.active {
  color: #ff6b6b;
  font-weight: bold;
}

.filter-item.active::after {
  content: '';
  position: absolute;
  bottom: -20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background: linear-gradient(to right, #ff9a9e, #ff6b6b);
  border-radius: 2rpx;
}

.merchant-list {
  padding: 20rpx;
}

.merchant-item {
  display: flex;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.merchant-logo {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.merchant-info {
  flex: 1;
}

.merchant-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.merchant-rating {
  display: flex;
  align-items: center;
  margin-bottom: 10rpx;
}

.rating-score {
  font-size: 28rpx;
  color: #ff6b6b;
  font-weight: bold;
}

.rating-text {
  font-size: 24rpx;
  color: #ff6b6b;
  margin-right: 10rpx;
}

.sales-text {
  font-size: 24rpx;
  color: #999;
}

.merchant-meta {
  display: flex;
  font-size: 24rpx;
  color: #999;
}

.distance {
  margin-right: 20rpx;
}

/* 空状态 */
.empty-state {
  padding: 60rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
